<template>
    <div class="marketing_group_detail_statistics">
        <h1>数据概览</h1>
        <el-row class="preview-custom-row">
            <el-col
                :span="totalCols.length > 3 ? 6 : 8"
                v-for="{ label, prop } in totalCols"
                :key="label"
                class="preview-custom-col">
                <span>{{ statisticBasic[prop] || 0 }}</span>
                <span>
                    {{ label }}
                    <!-- todo:tip -->
                    <el-tooltip v-if="prop === 'joinUserNewNum'" effect="dark" placement="right">
                        <template #content> 通过参与抽奖活动，注册新用户。 </template>
                        <el-icon v-if="prop === 'joinUserNewNum'"><Warning /></el-icon>
                    </el-tooltip>
                </span>
            </el-col>
        </el-row>
        <h1>抽奖记录</h1>
        <!-- tab -->
        <el-tabs v-model="activityType" @tab-change="handleTabChange">
            <el-tab-pane v-for="{ name, label } in luckyTabs" :key="name" :label="label" :name="name"></el-tab-pane>
        </el-tabs>
        <template v-if="activityType == 1">
            <div class="zw-form-layout">
                <el-form ref="formRef" :model="form" @submit.prevent>
                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item prop="keywords">
                                <el-input
                                    v-model="form.keywords"
                                    clearable
                                    placeholder="根据昵称、会员手机号查询"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="16" class="zw-form-btns">
                            <div>
                                <el-button type="primary" v-auth="'lottery_list:view'" @click="searchHandler"
                                    >查询</el-button
                                >
                                <el-button plain @click="resetHandler">清空</el-button>
                            </div>
                            <div class="export-btn">
                                共{{ totalCount || 0 }}条数据
                                <el-button v-auth="'lottery_list:export'" plain @click="handleExport">导出</el-button>
                            </div>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <!-- 列表 -->
            <el-table :data="tableList" key="1" :stripe="true" class="statistics-table">
                <el-table-column
                    v-for="{ prop, label, width } in tableColumns"
                    :key="prop"
                    :label="label"
                    :prop="prop"
                    :width="width || 'auto'">
                    <template #default="{ row }">
                        <template v-if="prop === 'drawUserInfo'">
                            {{ row?.drawUserInfo?.nickname }}({{ row?.drawUserInfo?.mobile }})
                        </template>
                        <template v-if="prop === 'operation'">
                            <el-button size="small" @click.stop="handleRecord(row)"> 抽奖记录 </el-button>
                        </template>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div style="margin-top: 15px">
                <Pagination
                    :total="totalCount"
                    :page-size="form.perPage"
                    :current-page="form.page"
                    @sizeChange="changeSizeHandler"
                    @pageChange="changePageHandler" />
            </div>
        </template>
        <template v-if="activityType == 2">
            <div class="zw-form-layout">
                <el-form ref="formReRef" :model="recordForm" @submit.prevent>
                    <el-row :gutter="24">
                        <el-col :span="5">
                            <el-form-item prop="keywords">
                                <el-input
                                    v-model="recordForm.keywords"
                                    clearable
                                    placeholder="输入昵称、手机号查"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-select v-model="recordForm.awardStauts" clearable placeholder="领奖状态">
                                <el-option
                                    v-for="item in luckyAwardStauts"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="5">
                            <el-select v-model="recordForm.receiveAwardSonStauts" clearable placeholder="子状态">
                                <el-option
                                    v-for="item in receiveAwardSonStauts"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="9" class="zw-form-btns">
                            <div>
                                <el-button type="primary" v-auth="'lottery_list:view'" @click="searchReHandler"
                                    >查询</el-button
                                >
                                <el-button plain @click="resetReHandler">清空</el-button>
                            </div>
                            <div class="export-btn">
                                共{{ recordTotalCount || 0 }}条数据
                                <el-button v-auth="'lottery_list:export'" plain @click="handleReExport">导出</el-button>
                            </div>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <!-- 列表 -->
            <el-table key="2uu" :data="recordTableList" :stripe="true" class="statistics-table">
                <el-table-column
                    v-for="{ prop, label, width } in recordTableColumns"
                    :key="prop"
                    :label="label"
                    :prop="prop"
                    :width="width || 'auto'">
                    <template #default="{ row }">
                        <template v-if="prop === 'drawUserInfo'">
                            {{ row?.drawUserInfo?.nickname }}
                        </template>
                        <template v-if="prop === 'operation'">
                            <el-button v-if="row.receiveAwardSonStatus == 5" size="small" @click="handleSend(row)">
                                立即发货
                            </el-button>
                            <el-button v-if="row.receiveAwardSonStatus == 2" size="small" @click="handleConfirm(row)">
                                确定取货
                            </el-button>
                            <el-button v-if="row.receiveAwardSonStatus == 6" size="small" @click="handleInfo(row)">
                                发货信息
                            </el-button>
                        </template>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div style="margin-top: 15px">
                <Pagination
                    :total="recordTotalCount"
                    :page-size="recordForm.perPage"
                    :current-page="recordForm.page"
                    @sizeChange="changeReSizeHandler"
                    @pageChange="changeRePageHandler" />
            </div>
        </template>
        <InfoDialog ref="infoDialog"></InfoDialog>
        <SendDialog ref="sendDialog" @handle-confirm="queryCouponListHandlerCopy"></SendDialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import constants from '@/commons/constants';
import { useRouter } from 'vue-router';
import { packSelectObjUtil, exportExc, format } from '@/commons/utils';
import request from '@/request/index';
import Pagination from '@/components/Pagination.vue';
import InfoDialog from './infoDialog.vue';
import SendDialog from './sendDialog.vue';
import { configProviderProps, ElMessageBox, ElMessage } from 'element-plus';
import { cloneDeep } from '../../../../../commons/utils';

const luckyAwardStauts = reactive(packSelectObjUtil(constants.LUCKY_AWARD_STAUTS));
const receiveAwardSonStauts = reactive(packSelectObjUtil(constants.LUCKY_RECEIVE_AWARD_SON_STAUTS));
const awardStauts = reactive(packSelectObjUtil(constants.AWARD_STAUTS));
const sendAwardMethod = reactive(packSelectObjUtil(constants.SEND_AWARD_METHOD));
const luckyAwardType = reactive(packSelectObjUtil(constants.LUCKY_AWARD_TYPE));

const router = useRouter();

const props = defineProps(['id', 'type', 'name']);

const form = reactive({
    page: 1, //分页页码，数字类型
    perPage: 10, //页记录数
    keywords: '' //搜索关键字
});
const formRef = ref(null);
const totalCount = ref(0);
let tableList = reactive([]);
const tableColumns = [
    { label: '抽奖人', prop: 'drawUserInfo' },
    { label: '抽奖次数', prop: 'drawNum' },
    { label: '中奖次数', prop: 'awardNum' },
    { label: '额外抽奖次数', prop: 'extraDrawNum' },
    { label: '操作', prop: 'operation', fixed: 'right', width: '100' }
];
let statisticBasic = reactive({});
let luckyTabs = reactive([
    { name: '1', label: '抽奖概况' },
    { name: '2', label: '抽奖记录' }
]);
let activityType = ref('1');
let recordTableList = reactive([]);
let recordTotalCount = ref(0);
const recordTableColumns = [
    { label: '抽奖时间', prop: 'awardTime', width: '180' },
    { label: '抽奖人', prop: 'drawUserInfo' },
    { label: '抽奖结果', prop: 'awardStautsText' },
    { label: '奖品名称', prop: 'awardName' },
    { label: '奖品类型', prop: 'awardTypeText' },
    { label: '奖品发放方式', prop: 'sendAwardMethodText' },
    { label: '领奖状态', prop: 'receiveAwardStatusName' },
    { label: '子状态', prop: 'receiveAwardSonStatusText' },
    { label: '操作', prop: 'operation', fixed: 'right', width: '100' }
];
let recordForm = reactive({
    awardUserId: '', //抽奖人用户ID
    keywords: '', //昵称或手机号
    awardStauts: 0, //1未中奖 2已中奖 0 全部
    receiveAwardSonStauts: 0, //1自动发放完成 2等待用户取货 3用户已取货 4等待用户填写地址 5等待商家发货 6商家已发货' 0 全部
    page: 1,
    perPage: 10
});
const recordFormClone = cloneDeep(recordForm);

const totalCols = computed(() => {
    const cols = [
        { label: '总参与用户数', prop: 'joinUserNum' },
        { label: '总抽奖次数', prop: 'luckDrawNum' },
        { label: '新用户', prop: 'joinUserNewNum' }
    ];
    return cols;
});
const infoDialog = ref();
const sendDialog = ref();

const handleTabChange = val => {
    if (val == 1) {
        searchHandler();
    } else {
        searchReHandler();
    }
};

/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    queryCouponListHandler();
};
const changeRePageHandler = page => {
    recordForm.page = page;
    queryCouponListHandlerCopy();
};
/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.perPage = perPage;
    queryCouponListHandler();
};
const changeReSizeHandler = perPage => {
    recordForm.page = 1;
    recordForm.perPage = perPage;
    queryCouponListHandlerCopy();
};
/**
 * 分页查询
 */
const queryCouponListHandler = async () => {
    const { data } = await request('activityDrawSurvey', { id: props.id, ...form });
    const list = data.list || [];
    tableList.length = 0;
    tableList.push(...list);
    totalCount.value = data.totalCount;
};
const queryCouponListHandlerCopy = async () => {
    const { data } = await request('activityDrawRecord', { id: props.id, ...recordForm });
    const list = (data.list || []).map(item => {
        item.awardStautsText = awardStauts[item.awardStatus]?.label;
        item.awardTypeText = luckyAwardType[item.awardType - 1]?.label;
        item.sendAwardMethodText = sendAwardMethod[item.sendAwardMethod - 1]?.label;
        item.receiveAwardSonStatusText = receiveAwardSonStauts[item.receiveAwardSonStatus]?.label;
        return item;
    });
    recordTableList.length = 0;
    recordTableList.push(...list);
    recordTotalCount.value = data.totalCount;
};
/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
    searchHandler();
};
const formReRef = ref();
const resetReHandler = () => {
    Object.assign(recordForm, recordFormClone);
    searchReHandler();
};

const handleConfirm = ({ id }) => {
    ElMessageBox.confirm('中奖人已到店取货吗?', '提示', {
        confirmButtonText: '是的',
        cancelButtonText: '没有',
        type: 'warning'
    }).then(async () => {
        await request('activityDrawConfirm', { id });
        ElMessage({
            type: 'success',
            message: '确认成功'
        });
        queryCouponListHandlerCopy();
    });
};
const handleInfo = ({ id }) => {
    infoDialog.value.handleDialog(id);
};
const handleSend = row => {
    sendDialog.value.handleDialog(row);
    queryCouponListHandlerCopy();
};

const nameRouteHandler = row => {
    const { href } = router.resolve({
        path: '/order/list/detail',
        query: {
            orderId: row.orderId
        }
    });
    window.open(href, '_blank');
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    queryCouponListHandler();
};
const searchReHandler = () => {
    recordForm.page = 1;
    recordForm.awardUserId = '';
    queryCouponListHandlerCopy();
};

const handleExport = async () => {
    const res = await request('exportActivityBasicData', { id: props.id, keywords: form.keywords });
    exportExc(res, props.name + '_抽奖概况记录_' + format(new Date(), 'YYYY-MM-DD_HH.mm.ss'));
};

const handleReExport = async () => {
    const res = await request('exportActivityDrawRecord', { id: props.id, ...recordForm });
    exportExc(res, props.name + '_抽奖记录_' + format(new Date(), 'YYYY-MM-DD_HH.mm.ss'));
};

const handleRecord = ({ awardUserId }) => {
    activityType.value = '2';
    recordForm.page = 1;
    recordForm.awardUserId = awardUserId;
    recordForm.keywords = '';
    recordForm.awardStauts = 0;
    recordForm.receiveAwardSonStauts = 0;
    queryCouponListHandlerCopy();
};

const getStatisticBasic = async () => {
    const { data } = await request('activityDrawBasicData', { id: props.id });
    Object.assign(statisticBasic, data);
};

// const getStatisticOrderList = async () => {
//     const { data } = await request('spellGroupStatisticOrderList', { id: props.id, ...form });
//     Object.assign(statisticBasic, data);
// };

const getAllData = () => {
    // getStatisticOrderList();
    getStatisticBasic();
    searchHandler();
};

onMounted(() => {
    getAllData();
});
</script>

<style lang="scss" scoped>
.marketing_group_detail_statistics {
    h1 {
        font-size: 14px;
        font-weight: 500;
        position: relative;
        padding-left: 15px;
        margin: 0;
        margin-top: 10px;
        display: flex;
        align-items: center;
        &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 15%;
            width: 3px;
            height: 70%;
            background-color: var(--el-color-primary);
        }
        &:last-of-type {
            margin-bottom: 16px;
        }
        :deep(.el-icon) {
            color: #33302d;
            margin-left: 4px;
        }
    }
    .preview-custom-row {
        margin: 30px 0;
    }
    .preview-custom-col {
        display: flex;
        justify-content: center;
        align-items: flex-start;
        flex-direction: column;
        /* & + div {
            border-left: 1px solid #eee;
        } */
        span {
            font-size: 24px;
            font-family: HelveticaNeue-Medium, HelveticaNeue;
            font-weight: 500;
            color: #333333;
            margin-bottom: 7px;
            & + span {
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #999999;
            }
        }
    }

    .zw-form-btns {
        display: flex;
        justify-content: space-between;
    }

    .zw-form-layout {
        background-color: #fff;
        border: 0;
        padding: 0;
    }

    .export-btn {
        color: #969696;
        font-size: 14px;
    }

    :deep {
        .statistics-table .el-table__cell {
            padding: 20px 0;
        }

        .el-table th.el-table__cell {
            padding: 12px 0;
        }
        .statistics-table .el-table__expanded-cell {
            background: #f9f9f9;
            padding: 0;
            &:hover {
                background: #f9f9f9 !important;
            }
        }
        .el-table {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #33302d;
        }
        .el-table th.el-table__cell {
            font-size: 14px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #33302d;
        }
    }
    .custom-el-link {
        display: inline;
        :deep .el-link__inner {
            display: inline;
        }
    }
}
</style>
